package com.zyz.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private static long expiration = 30 * 60 * 1000;
    private static String secretString = "YUdg+5EZXzh5DVffTZgfMoWVr+2SXK94zacY19IcCGk=";
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    // 生成令牌（token）
    public static String getJwt(Map<String,Object> claims) {
        String compact = Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(key)
                .compact();
        return compact;
    }

    // 校验令牌（token）
    public static Claims verify(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try{
            body = build.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            log.warn("token校验失败，超时");
        } catch (Exception e) {
            log.warn("token校验失败");
        }
        return body;

    }

    public static Integer getUserIdByToken(String token){
        log.info("getUserByToken.token:"+token);
        Claims claims = verify(token);
        Assert.notNull(claims,"claims为空");
        Integer userId = (Integer) claims.get("id");
        log.info("userId:"+userId);
        return userId;
    }
}
